package base.audio;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;

import base.GerenciadorConexoes;

public class AudioSocket {

	private DatagramSocket socketUDP;
	private InetAddress remote_ip;
	private int remote_port;
	
	
	public AudioSocket(InetAddress remote_ip, int remote_port, int local_port) {
		try {
			this.remote_ip = remote_ip;
			this.remote_port = remote_port;
			socketUDP = new DatagramSocket(local_port);
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		GerenciadorConexoes.getInstance().inserirAudioSocket(this);
	}
	
	@Override
	public boolean equals(Object obj) {
		AudioSocket skt = (AudioSocket) obj;
		return socketUDP.equals(skt.getSocketUDP());
	}

	public AudioSocket() {
		try {
			socketUDP = new DatagramSocket();
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void desativar(){
		this.socketUDP.close();
		GerenciadorConexoes.getInstance().removerAudioSocket(this);

	}

	public DatagramSocket getSocketUDP() {
		return socketUDP;
	}

	public InetAddress getRemoteIp() {
		return remote_ip;
	}


	public int getRemotePort() {
		return remote_port;
	}

	public AudioPacket receivePacket() throws IOException, SocketTimeoutException {
		AudioPacket retorno = null;

		byte[] receiveData = new byte[4000 + 14];
		DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

		this.socketUDP.receive(receivePacket);
		retorno = new AudioPacket(receivePacket.getData());
		retorno.setSenderIp(receivePacket.getAddress());
		retorno.setSenderPort(receivePacket.getPort());

		return retorno;
	}

	public void sendPacket(AudioPacket pkt) throws IOException {
		byte[] sendData = pkt.getBytes();
		DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, remote_ip, remote_port);
		// System.out.println("Enviando pacote de numseq="+pkt.getSeqNum());
		this.socketUDP.send(sendPacket);
	}
}
